# 用户服务维护脚本 (PowerShell版本)
# =====================================
# 
# 这个脚本提供了自动化的维护功能，包括：
# 1. 清理临时文件和缓存
# 2. 检查重复文件
# 3. 验证目录结构
# 4. 生成维护报告
#
# 使用方法：
#     .\scripts\user_service_maintenance.ps1 [参数]
#
# 参数：
#     -CleanCache          清理缓存文件
#     -CheckDuplicates     检查重复文件  
#     -ValidateStructure   验证目录结构
#     -FullMaintenance     执行完整维护
#     -GenerateReport      生成维护报告

param(
    [switch]$CleanCache,
    [switch]$CheckDuplicates,
    [switch]$ValidateStructure,
    [switch]$FullMaintenance,
    [switch]$GenerateReport,
    [string]$ServicePath = "backend\services\user_service"
)

# 初始化报告
$Report = @{
    Timestamp = Get-Date -Format "yyyy-MM-ddTHH:mm:ss"
    Actions = @()
    Warnings = @()
    Errors = @()
    Summary = @{}
}

function Write-ColorOutput {
    param([string]$Message, [string]$Color = "White")
    Write-Host $Message -ForegroundColor $Color
}

function Clean-CacheFiles {
    Write-ColorOutput "🧹 清理缓存文件..." "Cyan"
    
    $CachePatterns = @(
        "__pycache__",
        "*.pyc",
        "*.pyo", 
        ".pytest_cache",
        ".coverage",
        "htmlcov",
        "*.egg-info",
        "build",
        "dist",
        ".DS_Store",
        "Thumbs.db",
        "*.tmp",
        "*.temp"
    )
    
    $CleanedItems = @()
    
    foreach ($Pattern in $CachePatterns) {
        $Items = Get-ChildItem -Path $ServicePath -Recurse -Name $Pattern -Force -ErrorAction SilentlyContinue
        
        foreach ($Item in $Items) {
            $FullPath = Join-Path $ServicePath $Item
            try {
                if (Test-Path $FullPath -PathType Container) {
                    Remove-Item -Path $FullPath -Recurse -Force
                } else {
                    Remove-Item -Path $FullPath -Force
                }
                $CleanedItems += $FullPath
            }
            catch {
                $Report.Errors += "清理失败: $FullPath - $($_.Exception.Message)"
            }
        }
    }
    
    $Report.Actions += @{
        Action = "clean_cache"
        ItemsCleaned = $CleanedItems.Count
        Files = $CleanedItems | Select-Object -First 10
    }
    
    Write-ColorOutput "✅ 已清理 $($CleanedItems.Count) 个缓存文件/目录" "Green"
}

function Check-DuplicateFiles {
    Write-ColorOutput "🔍 检查重复文件..." "Cyan"
    
    $FileHashes = @{}
    $Duplicates = @{}
    
    # 排除的目录
    $ExcludeDirs = @(".git", "__pycache__", ".pytest_cache", "htmlcov", "logs")
    
    $Files = Get-ChildItem -Path $ServicePath -Recurse -File | Where-Object {
        $Exclude = $false
        foreach ($ExcludeDir in $ExcludeDirs) {
            if ($_.FullName -like "*\$ExcludeDir\*") {
                $Exclude = $true
                break
            }
        }
        -not $Exclude
    }
    
    foreach ($File in $Files) {
        try {
            $Hash = Get-FileHash -Path $File.FullName -Algorithm MD5
            $HashValue = $Hash.Hash
            
            if ($FileHashes.ContainsKey($HashValue)) {
                if (-not $Duplicates.ContainsKey($HashValue)) {
                    $Duplicates[$HashValue] = @($FileHashes[$HashValue])
                }
                $Duplicates[$HashValue] += $File.FullName
            } else {
                $FileHashes[$HashValue] = $File.FullName
            }
        }
        catch {
            $Report.Warnings += "无法读取文件: $($File.FullName) - $($_.Exception.Message)"
        }
    }
    
    if ($Duplicates.Count -gt 0) {
        Write-ColorOutput "⚠️  发现 $($Duplicates.Count) 组重复文件:" "Yellow"
        foreach ($Group in $Duplicates.Values) {
            Write-ColorOutput "  - $($Group -join ', ')" "Yellow"
        }
    } else {
        Write-ColorOutput "✅ 未发现重复文件" "Green"
    }
    
    $Report.Actions += @{
        Action = "check_duplicates"
        DuplicateGroups = $Duplicates.Count
        Duplicates = $Duplicates
    }
    
    return $Duplicates
}

function Validate-DirectoryStructure {
    Write-ColorOutput "📁 验证目录结构..." "Cyan"
    
    # Expected directory structure
    $ExpectedStructure = @{
        "api" = "API Layer"
        "config" = "Configuration Management"
        "containers" = "Dependency Injection Containers"
        "core" = "Core Dependencies"
        "database" = "Database Management"
        "deployment" = "Deployment Configuration"
        "exceptions" = "Exception Definitions"
        "health" = "Health Checks"
        "interfaces" = "Interface Definitions"
        "repositories" = "Data Access Layer"
        "schemas" = "Data Schemas"
        "security" = "Security Components"
        "services" = "Business Service Layer"
        "tests" = "Test Code"
        "utils" = "Utility Functions"
        "validation" = "Data Validation"
        "user_service_Doc" = "Technical Documentation"
    }
    
    # 必需的文件
    $RequiredFiles = @(
        "main.py",
        "requirements.txt",
        "__init__.py",
        "conftest.py"
    )
    
    $StructureValid = $true
    $MissingDirs = @()
    $MissingFiles = @()
    
    # 检查目录
    foreach ($Dir in $ExpectedStructure.Keys) {
        $DirPath = Join-Path $ServicePath $Dir
        if (-not (Test-Path $DirPath -PathType Container)) {
            $MissingDirs += "$Dir ($($ExpectedStructure[$Dir]))"
            $StructureValid = $false
        }
    }
    
    # 检查文件
    foreach ($File in $RequiredFiles) {
        $FilePath = Join-Path $ServicePath $File
        if (-not (Test-Path $FilePath -PathType Leaf)) {
            $MissingFiles += $File
            $StructureValid = $false
        }
    }
    
    if ($MissingDirs.Count -gt 0) {
        Write-ColorOutput "Missing directories: $($MissingDirs -join ', ')" "Yellow"
    }
    if ($MissingFiles.Count -gt 0) {
        Write-ColorOutput "Missing files: $($MissingFiles -join ', ')" "Yellow"
    }
    
    if ($StructureValid) {
        Write-ColorOutput "Directory structure validation passed" "Green"
    }
    
    $Report.Actions += @{
        Action = "validate_structure"
        Valid = $StructureValid
        MissingDirs = $MissingDirs
        MissingFiles = $MissingFiles
    }
    
    return $StructureValid
}

function Generate-MaintenanceReport {
    Write-ColorOutput "📊 生成维护报告..." "Cyan"
    
    # 统计信息
    $TotalFiles = (Get-ChildItem -Path $ServicePath -Recurse -Filter "*.py").Count
    $TotalDirs = (Get-ChildItem -Path $ServicePath -Recurse -Directory).Count
    
    $Report.Summary = @{
        TotalPythonFiles = $TotalFiles
        TotalDirectories = $TotalDirs
        ActionsPerformed = $Report.Actions.Count
        WarningsCount = $Report.Warnings.Count
        ErrorsCount = $Report.Errors.Count
    }
    
    # 生成报告文件
    $Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $ReportFile = "user_service_maintenance_report_$Timestamp.json"
    $LogsPath = Join-Path $ServicePath "logs"
    
    # 确保logs目录存在
    if (-not (Test-Path $LogsPath)) {
        New-Item -Path $LogsPath -ItemType Directory -Force | Out-Null
    }
    
    $ReportPath = Join-Path $LogsPath $ReportFile
    
    $Report | ConvertTo-Json -Depth 10 | Out-File -FilePath $ReportPath -Encoding UTF8
    
    Write-ColorOutput "✅ 维护报告已生成: $ReportPath" "Green"
    return $ReportPath
}

function Invoke-FullMaintenance {
    Write-ColorOutput "🔧 开始完整维护..." "Cyan"
    Write-ColorOutput ("=" * 50) "Cyan"
    
    Clean-CacheFiles
    Write-Host
    
    Check-DuplicateFiles
    Write-Host
    
    Validate-DirectoryStructure
    Write-Host
    
    $ReportPath = Generate-MaintenanceReport
    
    Write-ColorOutput ("=" * 50) "Cyan"
    Write-ColorOutput "🎉 完整维护完成!" "Green"
    Write-ColorOutput "📊 详细报告: $ReportPath" "Green"
}

# 主逻辑
if (-not (Test-Path $ServicePath)) {
    Write-ColorOutput "❌ 用户服务路径不存在: $ServicePath" "Red"
    exit 1
}

if ($FullMaintenance) {
    Invoke-FullMaintenance
} else {
    if ($CleanCache) {
        Clean-CacheFiles
    }
    
    if ($CheckDuplicates) {
        Check-DuplicateFiles
    }
    
    if ($ValidateStructure) {
        Validate-DirectoryStructure
    }
    
    if ($GenerateReport) {
        Generate-MaintenanceReport
    }
    
    if (-not ($CleanCache -or $CheckDuplicates -or $ValidateStructure -or $GenerateReport)) {
        Write-ColorOutput "请指定至少一个操作选项:" "Yellow"
        Write-ColorOutput "  -CleanCache          清理缓存文件" "White"
        Write-ColorOutput "  -CheckDuplicates     检查重复文件" "White"
        Write-ColorOutput "  -ValidateStructure   验证目录结构" "White"
        Write-ColorOutput "  -FullMaintenance     执行完整维护" "White"
        Write-ColorOutput "  -GenerateReport      生成维护报告" "White"
    }
}
